// 获取 Notify 组件
import Notify from '@vant/weapp/notify/notify';

// 初始空数据结构，将在页面加载时替换为从API获取的真实数据
let roomBookingData = {};

Page({
    /**
     * 页面的初始数据
     */
    data: {
        searchKeyword: '',
        selectedDate: '',
        weekDayText: '',
        buildingIndex: 0,
        buildingList: [
            { id: 0, name: '全部' },
            { id: 1, name: '建筑·楼层' }
        ],
        timeHours: ['8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
        roomList: [
            {
                id: '401',
                name: '401',
                capacity: 10,
                equipment: '暂无相关设备',
                needApproval: true,
                phone: '12345678901',
                location: '四楼401会议室',
                timeSlots: []
            },
            {
                id: '709',
                name: '709',
                capacity: 30,
                equipment: '投影仪',
                needApproval: true,
                phone: '12345678902',
                location: '七楼709会议室',
                timeSlots: []
            },
            {
                id: '705',
                name: '705',
                capacity: 8,
                equipment: '投影仪',
                needApproval: true,
                phone: '12345678903',
                location: '七楼705会议室',
                timeSlots: []
            },
            {
                id: '302',
                name: '302',
                capacity: 10,
                equipment: '暂无相关设备',
                needApproval: true,
                phone: '12345678904',
                location: '三楼302会议室',
                timeSlots: []
            },
            {
                id: '305',
                name: '305安全质量文化教育室',
                capacity: 15,
                equipment: '电视',
                needApproval: true,
                phone: '12345678905',
                location: '三楼305会议室',
                timeSlots: []
            },
            {
                id: '407',
                name: '407',
                capacity: 10,
                equipment: '暂无相关设备',
                needApproval: true,
                phone: '12345678906',
                location: '四楼407会议室',
                timeSlots: []
            }
        ],
        showRoomDetail: false,
        currentRoom: {},
        availableTimeSlots: [],
        selectedTimeSlot: '',
        isLoading: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.initDate();
        this.fetchReservationData();
    },

    /**
     * 获取预约数据
     */
    fetchReservationData: function () {
        const app = getApp();
        wx.showLoading({
            title: '加载数据中...',
        });

        // 获取当前选择的日期格式化为YYYY-MM-DD
        const now = new Date();
        const year = now.getFullYear();
        let dateStr = this.data.selectedDate || '';
        dateStr = dateStr.replace('月', '-').replace('日', '');
        const formattedDate = `${year}-${dateStr}`;

        wx.request({
            url: `${app.globalData.baseUrl}/api/reservation/today`,
            method: 'GET',
            data: {
                date: formattedDate
            },
            header: {
                'content-type': 'application/json',
                'Authorization': wx.getStorageSync('token')
            },
            success: (res) => {
                if (res.data && res.data.code === 0) {
                    // 转换API返回的数据格式为本地需要的格式
                    this.processApiData(res.data.data);
                } else {
                    // 处理API错误
                    console.error('获取预约数据失败:', res.data);
                    Notify({ type: 'danger', message: '获取预约数据失败' });
                    // 使用默认空数据
                    roomBookingData = this.getDefaultEmptyData();
                }
            },
            fail: (err) => {
                console.error('请求预约数据失败:', err);
                Notify({ type: 'danger', message: '网络请求失败' });
                // 使用默认空数据
                roomBookingData = this.getDefaultEmptyData();
            },
            complete: () => {
                wx.hideLoading();
                this.setData({ isLoading: false });
                // 根据获取的数据生成时间槽
                this.generateTimeSlots();
            }
        });
    },

    /**
     * 处理API返回的数据
     */
    processApiData: function (apiData) {
        const formattedData = {};
        
        // 遍历API返回的数据，转换为适合本地使用的格式
        apiData.forEach(reservation => {
            const roomId = reservation.roomId;
            const startTime = new Date(reservation.startTime);
            const endTime = new Date(reservation.endTime);
            
            // 初始化房间数据结构
            if (!formattedData[roomId]) {
                formattedData[roomId] = {
                    myBookings: [],
                    otherBookings: []
                };
            }
            
            // 计算时间槽值
            // 例如：开始时间是16:30，结束时间是18:00
            // 需要标记时间槽：16.5, 17, 17.5
            const startHour = startTime.getHours();
            const startMinute = startTime.getMinutes();
            const endHour = endTime.getHours();
            const endMinute = endTime.getMinutes();
            
            // 计算开始时间对应的时间值
            const startTimeValue = startHour + (startMinute >= 30 ? 0 : 0.5);
            
            // 计算结束时间对应的时间值
            const endTimeValue = endHour + (endMinute > 0 ? 0 : 0.5);
            
            // 生成这个预约占用的所有时间槽
            for (let timeValue = startTimeValue; timeValue < endTimeValue; timeValue += 0.5) {
                // 检查是否是我的预约
                if (reservation.isMyBooking) {
                    formattedData[roomId].myBookings.push(timeValue);
                } else {
                    formattedData[roomId].otherBookings.push(timeValue);
                }
            }
        });
        
        // 更新全局变量
        roomBookingData = formattedData;
    },

    /**
     * 获取默认的空数据结构
     */
    getDefaultEmptyData: function () {
        const emptyData = {};
        this.data.roomList.forEach(room => {
            emptyData[room.id] = {
                myBookings: [],
                otherBookings: []
            };
        });
        return emptyData;
    },

    /**
     * 初始化日期
     */
    initDate: function () {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()];
        
        this.setData({
            selectedDate: `${month}月${day}日`,
            weekDayText: weekDay
        });
    },

    /**
     * 生成时间槽占用数据
     */
    generateTimeSlots: function () {
        // 获取当前时间，用于确定哪些时段不可预约
        const now = new Date();
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        const currentDateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
        const selectedDateStr = this.data.selectedDate.replace('月', '-').replace('日', '');
        const selectedDateFull = `${now.getFullYear()}-${selectedDateStr}`;
        
        // 检查是否是今天的日期
        const isToday = currentDateStr === selectedDateFull;
        
        const roomList = this.data.roomList.map(room => {
            // 获取此会议室的预定模式
            const pattern = roomBookingData[room.id] || { myBookings: [], otherBookings: [] };
            
            // 生成时间槽 - 使用半小时为单位
            const timeSlots = [];
            
            // 从8点到23点，生成每半小时的时间槽
            // 例如 8:00-8:30, 8:30-9:00, 9:00-9:30...
            for (let i = 8; i <= 23; i++) {
                for (let minute = 0; minute < 60; minute += 30) {
                    // 生成时间段标识，格式为 "HH:MM"
                    const timeStr = formatTimePoint(i, minute);
                    const nextTimeStr = minute === 0 ? 
                                        formatTimePoint(i, 30) : 
                                        formatTimePoint(i + 1, 0);
                    const timeSlotId = `${timeStr}-${nextTimeStr}`;
                    
                    // 检查此时间段是否已过期
                    let isPastTime = false;
                    if (isToday) {
                        if (i < currentHour || (i === currentHour && minute < currentMinute)) {
                            isPastTime = true;
                        }
                    }
                    
                    // 创建半小时时间值
                    // 整数表示当前小时的后半段，如16表示16:30-17:00
                    // 小数部分0.5表示当前小时的前半段，如16.5表示16:00-16:30
                    const timeValue = i + (minute === 0 ? 0.5 : 0);
                    
                    // 检查时间段是否被预定
                    const bookedByMe = pattern.myBookings.includes(timeValue);
                    const bookedByOthers = pattern.otherBookings.includes(timeValue);
                    
                    // 计算时间槽的位置
                    // 总共有 32 个半小时时间段 (8:00-24:00)
                    // 每个时间段宽度为 100/16 = 6.25% (对应整点刻度)
                    // 每个半小时时间段宽度为 3.125%
                    const slotIndex = (i - 8) * 2 + (minute === 0 ? 0 : 1);
                    // 调整位置以确保与时间刻度完美对齐
                    const position = `${slotIndex * 3.225}%`;
                    const width = "3.225%"; // 增加宽度以便更清晰地显示
                    
                    timeSlots.push({
                        time: i,
                        minute: minute,
                        timeSlotId: timeSlotId,
                        timeValue: timeValue,
                        available: !isPastTime && !bookedByMe && !bookedByOthers,
                        isPastTime: isPastTime && !bookedByMe && !bookedByOthers, // 仅当没有被预约时才显示为过期灰色
                        bookedByMe: bookedByMe, // 无论是否过期，都显示蓝色
                        bookedByOthers: bookedByOthers, // 无论是否过期，都显示橙色
                        position: position,
                        width: width
                    });
                }
            }
            
            return { ...room, timeSlots };
        });

        this.setData({ roomList });
    },

    /**
     * 搜索输入处理
     */
    onSearchInput: function (e) {
        this.setData({
            searchKeyword: e.detail.value
        });
        // 可以在这里添加搜索逻辑
    },

    /**
     * 日期选择处理
     */
    onDateChange: function (e) {
        const dateValue = e.detail.value; // 格式: YYYY-MM-DD
        const [year, month, day] = dateValue.split('-');
        const date = new Date(year, month - 1, day);
        const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];

        this.setData({
            selectedDate: `${month}月${day}日`,
            weekDayText: weekDay
        });

        // 重新获取对应日期的预约数据
        this.fetchReservationData();
    },

    /**
     * 建筑楼层选择处理
     */
    onBuildingChange: function (e) {
        this.setData({
            buildingIndex: e.detail.value
        });
        // 可以在这里添加筛选逻辑
    },

    /**
     * 会议室选择处理
     */
    onRoomSelect: function (e) {
        const roomId = e.currentTarget.dataset.id;
        const roomIndex = e.currentTarget.dataset.index;
        const selectedRoom = this.data.roomList[roomIndex];
        
        // 获取当前时间
        const now = new Date();
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        
        // 获取此会议室的预定模式
        const pattern = roomBookingData[roomId] || { myBookings: [], otherBookings: [] };
        
        
        // 生成30分钟间隔的时间段列表
        const availableTimeSlots = [];
        
        // 从当前时间开始遍历，以30分钟为单位生成时间段
        for (let hour = currentHour; hour < 23; hour++) {
            // 对于当前小时，根据分钟确定从哪个时间段开始
            const startMinute = (hour === currentHour) ? 
                               (currentMinute < 30 ? 0 : 30) : 0;
            
            // 在当前小时生成时间段
            for (let minute = startMinute; minute < 60; minute += 30) {
                // 创建半小时时间值
                // 整数表示当前小时的后半段，如16表示16:30-17:00
                // 小数部分0.5表示当前小时的前半段，如16.5表示16:00-16:30
                const timeValue = hour + (minute === 0 ? 0.5 : 0);
                const timeRange = formatTimeRange(
                    hour, minute, 
                    minute === 0 ? hour : hour + 1, 
                    minute === 0 ? 30 : 0
                );
                
                // 检查此时间段是否已被预订
                // 确保使用的是精确的timeValue值匹配
                const exactTimeValue = Number(timeValue.toFixed(1)); // 确保精确到小数点后一位
                const bookedByMe = pattern.myBookings.includes(exactTimeValue);
                
                // 添加调试信息，验证timeValue与timeRange的关系
                console.log(`Room ${roomId}: timeValue = ${exactTimeValue}, timeRange = ${timeRange}, bookedByMe = ${bookedByMe}`);
                
                const bookedByHarry = 
                    (roomId === '401' && timeValue === 14) || 
                    ((roomId === '709' || roomId === '705') && timeValue === 17);
                const bookedByOthers = pattern.otherBookings.includes(timeValue);
                
                // 确保未来的时间才能预订
                const isPastTime = (hour < currentHour) || (hour === currentHour && minute < currentMinute);
                
                availableTimeSlots.push({
                    timeRange: timeRange,
                    timeValue: timeValue,
                    isBooked: bookedByMe || bookedByHarry || bookedByOthers || isPastTime,
                    bookedByMe: bookedByMe,
                    bookedByHarry: bookedByHarry,
                    bookedByOthers: bookedByOthers,
                    isPastTime: isPastTime && !bookedByMe && !bookedByHarry && !bookedByOthers, // 仅当没有被预约时才显示为过期
                    isSelected: false
                });
            }
        }
        
        this.setData({
            currentRoom: selectedRoom,
            availableTimeSlots: availableTimeSlots,
            showRoomDetail: true
        });
    },

    /**
     * 关闭会议室详情弹窗
     */
    onCloseRoomDetail: function () {
        this.setData({
            showRoomDetail: false
        });
    },

    /**
     * 时间段选择
     */
    onTimeSlotSelect: function (e) {
        const selectedTimeSlot = e.detail.value;
        
        // 检查所选时间段是否已被预订
        const selectedSlot = this.data.availableTimeSlots.find(slot => 
            slot.timeRange === selectedTimeSlot
        );
        
        if (selectedSlot && selectedSlot.isBooked) {
            // 已被预订的时间段不能选择
            Notify({ type: 'warning', message: '该时间段已被预订，请选择其他时间' });
            return;
        }
        
        // 更新所有时间段的选中状态
        const availableTimeSlots = this.data.availableTimeSlots.map(slot => {
            return {
                ...slot,
                isSelected: slot.timeRange === selectedTimeSlot
            };
        });
        
        this.setData({
            selectedTimeSlot: selectedTimeSlot,
            availableTimeSlots: availableTimeSlots
        });
    },

    /**
     * 预约会议室
     */
    onReserveRoom: function () {
        if (!this.data.selectedTimeSlot) {
            Notify({ type: 'warning', message: '请选择预约时间段' });
            return;
        }
        
        // 获取所选时间段是否已被预订
        const selectedSlot = this.data.availableTimeSlots.find(slot => 
            slot.timeRange === this.data.selectedTimeSlot
        );
        
        if (selectedSlot && selectedSlot.isBooked) {
            Notify({ type: 'danger', message: '该时间段已被预订' });
            return;
        }
        
        // 模拟预约成功
        Notify({ type: 'success', message: `成功预约${this.data.currentRoom.name}会议室，时间：${this.data.selectedTimeSlot}` });
        
        // 关闭弹窗
        setTimeout(() => {
            this.setData({
                showRoomDetail: false
            });
        }, 1500);
    },

    /**
     * 拨打电话
     */
    makeCall: function (e) {
        const phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone,
            fail(err) {
                Notify({ type: 'danger', message: '拨打电话失败' });
                console.error('拨打电话失败', err);
            }
        });
    },

    /**
     * 查看位置
     */
    viewLocation: function (e) {
        const location = e.currentTarget.dataset.location;
        Notify({ type: 'primary', message: `位置: ${location}` });
        // 这里可以实现导航或地图显示功能
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
    }
});

// 辅助函数 - 格式化时间点为 "HH:MM" 格式
function formatTimePoint(hour, minute) {
    return `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
}

// 辅助函数 - 格式化时间范围为 "HH:MM-HH:MM" 格式
function formatTimeRange(startHour, startMinute, endHour, endMinute) {
    const formatHour = (hour) => hour.toString().padStart(2, '0');
    const formatMinute = (minute) => minute.toString().padStart(2, '0');
    return `${formatHour(startHour)}:${formatMinute(startMinute)}-${formatHour(endHour)}:${formatMinute(endMinute)}`;
} 